const express = require('express');
const mongoose = require('mongoose');
const cors = require('cors');
const swaggerJsdoc = require('swagger-jsdoc');
const swaggerUi = require('swagger-ui-express');
const authRoutes = require('./routes/auth');
const { auth, checkRole } = require('./middleware/auth');

require('dotenv').config();

const app = express();

// 中间件
app.use(cors());
app.use(express.json());

// 连接MongoDB
mongoose.connect(process.env.MONGODB_URI)
  .then(() => console.log('Connected to MongoDB'))
  .catch(err => console.error('Could not connect to MongoDB', err));

// Swagger配置
const options = {
  definition: {
    openapi: '3.0.0',
    info: {
      title: '学生成绩管理系统API',
      version: '1.0.0',
      description: '学生成绩管理系统的RESTful API文档'
    },
    servers: [
      {
        url: 'http://localhost:3000',
        description: '开发服务器'
      }
    ]
  },
  apis: ['./index.js']
};

const specs = swaggerJsdoc(options);
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(specs));

// 路由
app.get('/', (req, res) => {
  res.send('学生成绩管理系统后端');
});

const Student = require('./models/Student');
const Grade = require('./models/Grade');
const User = require('./models/User');

// 学生信息CRUD路由
app.post('/students', async (req, res) => {
  try {
    const student = new Student(req.body);
    await student.save();
    res.status(201).send(student);
  } catch (err) {
    res.status(400).send(err);
  }
});

app.get('/students', async (req, res) => {
  try {
    const students = await Student.find();
    res.send(students);
  } catch (err) {
    res.status(500).send(err);
  }
});

app.get('/students/:id', async (req, res) => {
  try {
    const student = await Student.findOne({ studentId: req.params.id });
    if (!student) return res.status(404).send();
    res.send(student);
  } catch (err) {
    res.status(500).send(err);
  }
});

app.patch('/students/:id', async (req, res) => {
  try {
    const student = await Student.findByIdAndUpdate(req.params.id, req.body, { new: true });
    if (!student) return res.status(404).send();
    res.send(student);
  } catch (err) {
    res.status(400).send(err);
  }
});

app.delete('/students/:id', async (req, res) => {
  try {
    const student = await Student.findByIdAndDelete(req.params.id);
    if (!student) return res.status(404).send();
    res.send(student);
  } catch (err) {
    res.status(500).send(err);
  }
});

// 学生成绩CRUD路由
app.post('/grades', async (req, res) => {
  try {
    const grade = new Grade(req.body);
    await grade.save();
    res.status(201).send(grade);
  } catch (err) {
    res.status(400).send(err);
  }
});

app.get('/grades', async (req, res) => {
  try {
    const grades = await Grade.find();
    res.send(grades);
  } catch (err) {
    res.status(500).send(err);
  }
});

app.get('/grades/:studentid', async (req, res) => {
  try {
    const grade = await Grade.find({ studentId: req.params.studentid });
    if (!grade) return res.status(404).send();
    res.send(grade);
  } catch (err) {
    res.status(500).send(err);
  }
});

app.patch('/grades/:id', async (req, res) => {
  try {
    const grade = await Grade.findByIdAndUpdate(req.params.id, req.body, { new: true });
    if (!grade) return res.status(404).send();
    
    // 重新计算该学生的总成绩
    const studentGrades = await Grade.find({ studentId: grade.studentId });
    const totalScore = studentGrades.reduce((sum, g) => sum + g.score, 0);
    
    // 更新学生的总成绩
    await Student.findOneAndUpdate(
      { studentId: grade.studentId },
      { totalScore: totalScore }
    );
    
    res.send(grade);
  } catch (err) {
    res.status(400).send(err);
  }
});

app.delete('/grades/:id', async (req, res) => {
  try {
    const grade = await Grade.findByIdAndDelete(req.params.id);
    if (!grade) return res.status(404).send();
    res.send(grade);
  } catch (err) {
    res.status(500).send(err);
  }
});




// 路由
app.use('/api/auth', authRoutes);

// 学生列表路由 - 需要教师权限
app.get('/api/students', auth, checkRole(['teacher']), async (req, res) => {
  try {
    const students = await Student.find();
    res.json(students);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

// 学生详情路由 - 需要认证
app.get('/api/students/:id', auth, async (req, res) => {
  try {
    const student = await Student.findOne({ studentId: req.params.id });
    if (!student) {
      return res.status(404).json({ error: '学生不存在' });
    }

    // 检查权限
    if (req.user.role === 'user' && req.user.studentId !== req.params.id) {
      return res.status(403).json({ error: '没有权限访问该学生信息' });
    }

    res.json(student);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

// 错误处理中间件
app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).json({ error: '服务器内部错误' });
});



const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});